package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.model.Partner;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.PartnerService;
import com.cipe.cmrs.service.UserService;

@Controller
public class PartnerController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;

	@Autowired
	private PartnerService partnerService;

	@Autowired
	private CountryService countryService;
	@Autowired
	private UserService userService;

	@RequestMapping("/secure/savePartner.do")
	public String SavePartner(@ModelAttribute("partner") Partner partner, BindingResult result, Model model, HttpServletRequest request) {
		Boolean fromProject = partner.getFromProject();
		if (!result.hasErrors()) {
			try {
				partner = partnerService.savePartner(partner, getUserId(request));

			} catch (Exception e) {
				logger.error(getText("error.transaction"), e);
				saveError(request, getText("error.transaction"));
			}
		}
		if (null != fromProject) {
			if (fromProject == true) {
				return "redirect:/secure/showAddCipeprojectWithPartner.do?partnerId=" + partner.getId();
			} else {
				return "redirect:/secure/showAddPartnergrantWithPartner.do?partnerId=" + partner.getId();
			}
		}
		model.addAttribute("countryList", countryService.findAll());
		saveMessage(request, getText("editPartner.message.success"));
		model.addAttribute("partner", partner);
		return "editPartner";
	}

	@RequestMapping("/secure/showAddPartner.do")
	public String showAddPartner(Model model, @RequestParam("fromProject") Boolean fromProject) {
		Partner partner = new Partner();
		partner.setFromProject(fromProject);
		model.addAttribute("partner", partner);
		model.addAttribute("countryList", countryService.findAll());
		return "editPartner";
	}

	@RequestMapping("/secure/showEditPartner.do")
	public String showEditPartner(@RequestParam Integer id, Model model) {
		model.addAttribute("partner", partnerService.findById(id));
		return "editPartner";
	}

	@RequestMapping("/secure/showPartnerList.do")
	public String showPartnerList(Model model) {
		model.addAttribute("partners", partnerService.findAll());
		return "partnerList";
	}
}
